#pragma once

#include <boost/asio.hpp>
#include <tbb/pipeline.h>

#include "PollFilter.h"
#include "WorkFilter.h"
#include "WorkManager.h"


// Forward declaration
class TcpConnection;


/// The top-level class of the HTTP server
class TcpServer
{
public:
	/// Constructs the server to listen to the specified port
	TcpServer(unsigned short port = 80, bool showStat = false);

	/// Disposes allocated resources
	~TcpServer();

	/// Run the server's io_service loop
	void Run();

private:
	/// Handles completion of an asynchronous accept operation
	void HandleAccept(const boost::system::error_code &error);

	/// Starts asynchronous accept operation
	void StartAccept();

	/// The io_service used to perform asynchronous operations.
	boost::asio::io_service _ioService;

	/// Acceptor used to listen for incoming connections
	boost::asio::ip::tcp::acceptor _acceptor;

	/// Work manager
	WorkManager _workManager;

	/// The next connection to be accepted.
	TcpConnection *_newConnection;

	/// Pipeline which parses results of async requests
	tbb::pipeline _pipeline;

	/// Pipeline filter which polls ioservice events
	PollFilter _pollFilter;

	/// Shows whether the server should display statistics
	bool _showStat;

	/// Pipeline filter which processes works of connections
	WorkFilter _workFilter;
};
